package com.leetcode.problems016;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public int threeSumClosest(int[] nums, int target) {
        //先进行排序
        Arrays.sort(nums);
        int minDiff = Integer.MAX_VALUE;
        int minDiffSum = 0;
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            while(l < r){
                int sum = nums[i] + nums[l] + nums[r];
                int diff = Math.abs(sum - target);
                if(minDiff >= diff){
                    minDiff = diff;
                    minDiffSum = sum;
                }
                if( sum == target){
                    return sum;
                }else if (sum < target){
                    l++;
                }else if (sum > target){
                    r--;
                }
            }
        }
        return minDiffSum;
    }

    public static void main(String[] args) {
    }
}
